package com.gaofans.nrpc.common.compress;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import static com.gaofans.nrpc.common.compress.CodecFactory.GZIP;

/**
 * gzip编码器
 * @author GaoFans
 */
public class GzipCodec implements Codec{
    @Override
    public byte getMessageEncoding() {
        return GZIP;
    }

    @Override
    public byte[] decompress(byte[] in) throws IOException {
        try(ByteArrayOutputStream bos = new ByteArrayOutputStream();
            GZIPInputStream gzip = new GZIPInputStream(new ByteArrayInputStream(in))) {
            byte[] buffer = new byte[1024];
            int offset = -1;
            while ((offset = gzip.read(buffer)) != -1) {
                bos.write(buffer, 0, offset);
            }
            return bos.toByteArray();
        }
    }

    @Override
    public byte[] compress(byte[] out) throws IOException {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             GZIPOutputStream gzip = new GZIPOutputStream(bos)) {
            gzip.write(out);
            gzip.finish();
            return bos.toByteArray();
        }
    }
}
